package link.jfire.jnet.server.CompletionHandler;

import java.nio.channels.CompletionHandler;
import javax.annotation.Resource;
import link.jfire.baseutil.collection.buffer.ByteBuf;
import link.jfire.baseutil.simplelog.ConsoleLogFactory;
import link.jfire.baseutil.simplelog.Logger;
import link.jfire.jnet.common.result.InternalResultContainer;
import link.jfire.jnet.common.result.ServerInternalResult;
import link.jfire.jnet.server.server.ServerChannelInfo;

@Resource
public class ChannelWriteHandler implements CompletionHandler<Integer, ServerInternalResult>
{
	private final Logger logger = ConsoleLogFactory.getLogger();
	
	@Override
	public void completed(Integer writeTotal, ServerInternalResult result)
	{
		try
		{
			result.ensureMultithreadedVisibilityForRead();
			ByteBuf<?> buf = (ByteBuf<?>) result.getData();
			buf.addReadIndex(writeTotal);
			if (buf.remainRead() > 0)
			{
				if (logger.isTraceEnabled())
				{
					logger.trace("向通道{}数据写入不完整,写入{},当前状态{}", result.getChannelInfo().getAddress(), writeTotal, buf);
				}
				result.getChannelInfo().write(result);
				return;
			}
			else
			{
				buf.release();
				ServerChannelInfo channelInfo = result.getChannelInfo();
				channelInfo.sendOne();
				InternalResultContainer.recycleServer(result);
				ServerInternalResult next = channelInfo.waitForSend();
				if (next != null)
				{
					next.getChannelInfo().write(next);
				}
				else
				{
					logger.trace("消息是空的，通道剩余是{}", channelInfo.left());
				}
			}
		}
		catch (Exception e)
		{
			result.getChannelInfo().close(e);
		}
	}
	
	@Override
	public void failed(Throwable exc, ServerInternalResult result)
	{
		result.ensureMultithreadedVisibilityForRead();
		((ByteBuf<?>) result.getData()).release();
		result.getChannelInfo().close(exc);
	}
	
}
